import { BUNDLE_TYPE_ENUM } from "../base/EnumIndex";
import { Tools } from "../common/Tools";
import { ResManager } from "../manager/ResManager";
import { IScrewInfo } from "./LevelConfig";

export interface ICollectConfig {
    id: number;
    type: number;
    name: string;
    progress: number;
}

export default class GlobalData {

    // public static async setSpriteFrame(bundle: BUNDLE_TYPE_ENUM, name: string) {
    //     const spriteFrame = await ResManager.ins.loadRes(`texture/screw/${name}`, cc.SpriteFrame, bundle);
    // }

    public static levelId: number = 1;

    public static colors: string[] = [
        "#65f8f8", "#54c2fe", "#e67c8d", "#fc9af4",
        "#e487fe", "#ff6b55", "#bdfcaa", "#fefa5b",
    ];

    public static flyPos: cc.Vec2[][] = [
        [cc.v2(11, -15), cc.v2(-18, -9), cc.v2(14, 9), cc.v2(-15, 15)],
        [cc.v2(6, -29), cc.v2(-23, -23), cc.v2(11, -6), cc.v2(-18, 0), cc.v2(15, 17), cc.v2(-12, 23)],
        [cc.v2(3, -42), cc.v2(-26, -35), cc.v2(9, -19), cc.v2(-21, -13), cc.v2(14, 3), cc.v2(-16, 10), cc.v2(18, 26), cc.v2(-10, 33)],
    ];

    public static collectConfigs: ICollectConfig[] = [
        { id: 1, type: 0, progress: 0, name: "1" },
        { id: 2, type: 1, progress: 0, name: "1" },
        { id: 3, type: 2, progress: 0, name: "1" },
        { id: 4, type: 3, progress: 0, name: "1" },
        { id: 5, type: 0, progress: 0, name: "1" },
        { id: 6, type: 1, progress: 0, name: "1" },
        { id: 7, type: 2, progress: 0, name: "1" },
        { id: 8, type: 3, progress: 0, name: "1" },
        { id: 9, type: 0, progress: 0, name: "1" },
        { id: 10, type: 1, progress: 0, name: "1" },
        { id: 11, type: 2, progress: 0, name: "1" },
        { id: 12, type: 3, progress: 0, name: "1" },
        { id: 13, type: 0, progress: 0, name: "1" },
        { id: 14, type: 1, progress: 0, name: "1" },
        { id: 15, type: 2, progress: 0, name: "1" },
        { id: 16, type: 3, progress: 0, name: "1" },
        { id: 17, type: 0, progress: 0, name: "1" },
        { id: 18, type: 1, progress: 0, name: "1" },
        { id: 19, type: 2, progress: 0, name: "1" },
        { id: 20, type: 3, progress: 0, name: "1" },
        { id: 21, type: 0, progress: 0, name: "1" },
    ];
    public static getCollectConfigById(id: number) {
        const config = this.collectConfigs.find((o) => o.id === id);
        return config;
    }

    public static sleep(ms: number): Promise<void> {
        return new Promise<any>(function (resolve, reject) {
            setTimeout(function () {
                resolve(`sleep`);
            }, ms);
        });
    }

    /**
     * 矩形相交
     * @param node1 
     * @param node2 
     * @returns 
     */
    public static intersect(node1: cc.Node, node2: cc.Node) {
        if (!node1 || !node2) return false;
        const pos1 = node1.convertToWorldSpaceAR(cc.v2(0, 0));
        const pos2 = node2.convertToWorldSpaceAR(cc.v2(0, 0));
        if (Math.abs(pos1.x - pos2.x) < (node1.width + node2.width) / 2 &&
            Math.abs(pos1.y - pos2.y) < (node1.height + node2.height) / 2) {
            return true;
        }
        return false;
    }


    /**
     * 添加铰链
     * @param node 板块节点
     * @param screwInfo 螺丝对象
     * @param index 添加到板块的位置编号
     */
    public static addRevoluteJoint(node: cc.Node, screwInfo: IScrewInfo, index: number) {
        // console.log("addRevoluteJoint:", node);
        // console.log("screwInfo:", screwInfo);
        const boardBody = node.getComponent(cc.RigidBody);
        const screwBody = screwInfo.node.getComponent(cc.RigidBody);
        const boardCollider = node.getComponent(cc.PhysicsPolygonCollider);
        const revoluteJoint = node.addComponent(cc.RevoluteJoint);
        boardBody.awake = false;
        boardBody.gravityScale = 1;
        revoluteJoint.connectedBody = screwBody;
        revoluteJoint.anchor = node.getChildByName(`${index}`).getPosition();
        revoluteJoint.apply();
        boardBody.awake = true;
        boardCollider.apply();
        screwInfo.revoluteJoint = revoluteJoint;
    }

    /**
     * 移除铰链
     * @param screwInfo 
     */
    public static removeRevoluteJoint(screwInfo: IScrewInfo) {
        if (screwInfo.revoluteJoint !== null) {
            const revoluteJoint = screwInfo.revoluteJoint;
            const banzi = revoluteJoint.node;
            revoluteJoint.node.removeComponent(revoluteJoint);
            revoluteJoint.apply();
            screwInfo.node.removeComponent(cc.PhysicsPolygonCollider);
            screwInfo.node.removeComponent(cc.RigidBody);
            setTimeout(() => {
                banzi.getComponent(cc.RigidBody).fixedRotation = false;
                banzi.getComponent(cc.RigidBody).awake = true;
            }, 0);
            screwInfo.revoluteJoint = null;
        }
    }

    public static async setScrewSprite(screwInfo: IScrewInfo) {
        const sprite = screwInfo.node.children[0].getComponent(cc.Sprite);
        const sprite1 = screwInfo.node.children[1].getComponent(cc.Sprite);
        sprite.spriteFrame = await ResManager.ins.loadRes(`texture/screw/${screwInfo.color + '0'}`, cc.SpriteFrame, BUNDLE_TYPE_ENUM.GAME_PLAY);
        sprite1.spriteFrame = sprite.spriteFrame;
        screwInfo.node.children[0].opacity = 255;
    }

    /**
     * 判断螺丝是否被遮挡
     * @param screwInfo 
     * @returns 
     */
    public static isScrewHide(screwInfo: IScrewInfo) {
        let screw = screwInfo.node;
        if (!screw) {
            return true;
        }

        if (!screw.parent || !screw.parent.parent) {
            return false;
        }

        let layer = screw.parent.parent;
        let nodes = getSiblingNodesAfter(layer);
        let key = false;
        if (screwInfo.node) {
            nodes.map((layer) => {
                let boards = layer.children;
                for (let j = 0; j < boards.length; j++) {
                    // console.log('000' + luosi_obj.id);
                    if (screwInfo.node.parent != boards[j]) {
                        if (boards[j].name !== 'luosi_' && boards[j] && this.isInter(screwInfo.node, boards[j])) {
                            key = true;
                        }
                    }

                }
            })
        }

        return key;
        /**获取子节点上层的节点 */
        function getSiblingNodesAfter(a: cc.Node): cc.Node[] {
            // 确保节点a不是null或undefined，并且它有父节点  
            if (!a || !a.parent) {
                console.error("Node 'a' is null or does not have a parent.");
                return [];
            }

            // 获取节点a的父节点  
            const parentNode = a.parent;

            // 找到节点a在父节点子节点列表中的索引  
            const index = parentNode.children.indexOf(a);

            // 如果索引是-1，说明a不是parentNode的直接子节点，这通常不应该发生  
            if (index === -1) {
                console.error("Node 'a' is not a direct child of its parent.");
                return [];
            }

            // 创建一个数组来存储a后面的兄弟节点  
            const siblingNodesAfter: cc.Node[] = [];

            // 遍历父节点的子节点列表，从a的下一个节点开始收集  
            for (let i = index + 1; i < parentNode.children.length; i++) {
                siblingNodesAfter.push(parentNode.children[i]);
            }

            // 对收集到的兄弟节点进行逆序排序  
            siblingNodesAfter.reverse();

            return siblingNodesAfter;
        }
    }

    /**判断两个多边形是否相交 */
    public static isInter(a: cc.Node, b: cc.Node) {
        /**获取孔节点的包围盒坐标 */
        function GetNode_points(node: cc.Node) {
            if (!node || !node.getComponent(cc.PhysicsPolygonCollider)) {
                return [new cc.Vec2(Tools.random(-10000, 10000), Tools.random(-10000, 10000))]
            }
            let p = node.getComponent(cc.PhysicsPolygonCollider).points;
            //console.log("p");
            let pos = [];
            p.map((point, i) => {
                pos[i] = node.convertToWorldSpaceAR(point);
            })
            return pos;
        }
        let a_ = GetNode_points(a);
        let b_ = GetNode_points(b);
        return cc.Intersection.polygonPolygon(a_, b_);
    }
}